//
//  PasslockFile.m
//  Personal Passlock
//
//  Created by 杨岑 on 3/12/15.
//  Copyright (c) 2015 杨岑. All rights reserved.
//

#import "PasslockFile.h"
#import <CocoaSQLite.h>

@implementation PasslockFile
{
    CocoaSQLiteConnection* _db;
}

+ (instancetype)open:(NSString *)file
{
    return [[PasslockFile alloc] initWith:file];
}

+ (instancetype)openNew:(NSString *)file
{
    if ([[NSFileManager defaultManager] fileExistsAtPath:file])
    {
        return nil;
    }
    else
    {
        PasslockFile* c = [[PasslockFile alloc] initWith:file];
        [c setupTables];
        return c;
    }
}

- (instancetype)initWith:(NSString*)file
{
    self = [super init];
    if (self)
    {
        _db = [CocoaSQLiteConnection open:file];
    }
    return self;
}

#define SQL_CREATE_SETTINGS "create table if not exists settings\
(k text not null, v text, ts date default CURRENT_TIMESTAMP, constraint pk primary key (k));"

#define SQL_CREATE_PASSWORDS    "CREATE TABLE login(title text not null, user_name text not null, password text not null,host text not null, type text, hint text, memo text, OS TEXT, domain text, ts date default CURRENT_TIMESTAMP, constraint pk primary key (title));"




- (void)setupTables
{
    NSString* sql = @SQL_CREATE_SETTINGS SQL_CREATE_PASSWORDS;
    [_db execute:sql];
}

- (NSDictionary *)getTableColumns:(NSString *)tableName
{
    return [_db tableColumnsWithType:tableName];
}

@end
